<?php

declare(strict_types=1);
/**
 * This file is part of bearing-web.
 *
 * @link     https://www.bearing.cn/
 * @contact  tech@bearing.cn
 * @license  https://gitee.com/cppo/bearing_web/-/blob/master/README.md
 */

namespace common;

class Base
{
    /**
     * @var array 错误消息
     */
    protected static array $error = [];

    /**
     * 获取错误消息.
     *
     * @return array|mixed|string
     */
    public static function getError(mixed $num = null): mixed
    {
        if (is_null($num)) {
            return self::$error;
        }
        return self::$error[intval($num)] ?? Code::$msg[Code::ERROR];
    }

    /**
     * 设置缓存并加锁
     *
     * @param string $key 缓存key
     * @param int $expire 过期时间
     */
    public static function lock(string $key, mixed $value, int $expire = 300): bool
    {
        if (! $key) {
            return false;
        }
        if (is_array($value)) {
            $value = json_encode($value);
        }
        return ! empty(\Yii::$app->redis->set($key, $value, 'nx', 'ex', $expire));
    }

    /**
     * 删除锁
     *
     * @param mixed $key
     * @return mixed
     */
    public static function unlock(mixed $key): mixed
    {
        return \Yii::$app->redis->del($key);
    }

    /**
     * 设置缓存.
     *
     * @param string $key 缓存key
     * @param int $expire 过期时间
     */
    public static function cache(string $key, mixed $value, int $expire = 300): bool
    {
        if (! $key) {
            return false;
        }
        if (is_array($value)) {
            $value = json_encode($value);
        }
        return ! empty(\Yii::$app->redis->setex($key, $expire, $value));
    }

    /**
     * 设置错误消息.
     *
     * @return false
     */
    protected static function setError(string $msg = ''): bool
    {
        array_unshift(self::$error, $msg);
        return false;
    }
}
